package com.quectel.mobile.controller.forum;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.forum.ForumTopicBusiness;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.forum.dto.ForumTopicDto;
import com.quectel.core.module.forum.dto.mongo.ForumTopicCountDto;
import com.quectel.core.module.forum.service.ForumTopicBindingService;
import com.quectel.core.module.forum.service.ForumTopicService;
import com.quectel.core.module.forum.service.mongo.ForumPostService;
import com.quectel.core.module.forum.service.mongo.ForumTopicCountService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/5/15 9:24
 * @description new java file header...
 */
@RestController
@RequestMapping("forumTopic")
@Tag(name = "ForumTopicController", description = "发帖话题相关api")
public class ForumTopicController extends BaseController {


    @Autowired
    private ForumTopicBusiness forumTopicBusiness;

    @DubboReference
    private ForumTopicService forumTopicService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private ForumTopicBindingService forumTopicBindingService;
    @DubboReference
    private ForumTopicCountService forumTopicCountService;

    @DubboReference
    private ForumPostService forumPostService;


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @Operation(summary = "通过Id查询话题详情")
    public Response<ForumTopicDto> info(@PathVariable("id") Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        params.put(LambdaUtil.getFieldName(ForumTopicDto::getTenantId), String.valueOf(id));
        if (forumTopicService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumTopicDto forumTopicDto = forumTopicService.selectById(id);

        return Response.<ForumTopicDto>ok().wrap(forumTopicDto);
    }


    @GetMapping("queryList")
    @Operation(summary = "查询所有的话题列表")
    public Response<Page<ForumTopicCountDto>> queryList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "话题范围1小区2城市3全国") @RequestParam Byte queryRange,
            @Parameter(description = "话题类别") @RequestParam(value = "category", required = false) Byte category
    ) {
        //如果登录信息没有无法查询到village信息则返回空列表
        if(SessionHolder.getLoginMobileUserSession() ==null){
            return Response.<Page<ForumTopicCountDto>>ok().wrap(Page.empty(pageNo, pageSize));
        }
        VillageDto villageDto = villageService.selectCacheById(SessionHolder.getLoginMobileUserSession().getCurrentVillageId());
        if (villageDto == null) {
            return Response.error("无法查询到小区信息，请联系管理员");
        }

        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        //topic的一些限制
        HashMap<String, Object> topicParams = new HashMap<>(2);
        topicParams.put(LambdaUtil.getFieldName(ForumTopicDto::getStatus), String.valueOf(SystemConstants.NORMAL));
        if (category != null) {
            topicParams.put(LambdaUtil.getFieldName(ForumTopicDto::getCategory), String.valueOf(category));
        }

        StopWatch stopWatch = StopWatch.create("1");
        stopWatch.start();
        List<ForumTopicDto> forumTopicDtos = new ArrayList<>();
        //根据不同的范围查询topicList
        if (ForumConstants.ForumRange.VILLAGE.getRange().equals(queryRange)) {
            forumTopicDtos = forumTopicBusiness.getVillageTopic(Collections.singletonList(villageDto.getId()), topicParams);
        } else if (ForumConstants.ForumRange.CITY.getRange().equals(queryRange)) {
            forumTopicDtos = forumTopicBusiness.getCityTopic(villageDto.getTenantId(), villageDto.getCityCode(), topicParams);
        } else if (ForumConstants.ForumRange.ALL.getRange().equals(queryRange)) {
            forumTopicDtos = forumTopicBusiness.getAll(villageDto.getTenantId(), topicParams);
        }
        if (CollectionUtils.isEmpty(forumTopicDtos)) {
            return Response.<Page<ForumTopicCountDto>>ok().wrap(Page.empty(request.getPageNo(), request.getPageSize()));
        }
        stopWatch.stop();
        logger.debug("方法一耗时:" + stopWatch.getTotalTimeMillis());

        stopWatch.start();
        //查询话题数量
        request.put(ForumConstants.TOPICS, forumTopicDtos.stream().map(ForumTopicDto::getId).toArray());

        List<ForumTopicCountDto> forumTopicCountDtos = forumTopicCountService.queryList(request.getParams());
        stopWatch.stop();
        logger.debug("方法二耗时:" + stopWatch.getTotalTimeMillis());

        Page<ForumTopicCountDto> page = new Page<>(request.getPageNo(), request.getPageSize(), forumTopicDtos.size(), forumTopicCountDtos);
        return Response.<Page<ForumTopicCountDto>>ok().wrap(page);
    }
}
